package com.xinyue.server.framework.server.socket;

import com.alibaba.fastjson.JSON;
import com.xinyue.game.utils.encrypt.AESUtils;
import com.xinyue.game.utils.encrypt.GzipUtil;
import com.xinyue.server.framework.handler.GameServerEncryptService;
import com.xinyue.server.framework.handlermapping.GameHandlerMappingManager;
import com.xinyue.server.framework.handlermapping.IGameMessage;
import com.xinyue.server.framework.handlermapping.MessageClassKey;
import com.xinyue.server.framework.message.GameMessageHeader;
import com.xinyue.server.framework.message.GameMessagePackage;
import com.xinyue.server.framework.message.GameMessageType;
import com.xinyue.server.framework.server.common.GameMessageCodecService;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;

/**
 * @Author 王广帅
 * @Date 2021/5/30 19:33
 */
public class SocketDecoderHandler extends ChannelInboundHandlerAdapter {

    private Logger logger = LoggerFactory.getLogger(SocketDecoderHandler.class);



    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof ByteBuf) {
            ByteBuf byteBuf = (ByteBuf) msg;

            try {
                byte[] aesKey = GameServerEncryptService.getAesKey(ctx.channel());
                GameMessagePackage gameMessagePackage = GameMessageCodecService.decode(byteBuf,aesKey);
                ctx.fireChannelRead(gameMessagePackage);
            } catch (Throwable e) {
                logger.info("解析客户端请求异常，断开连接");
                ctx.fireExceptionCaught(e);
                ctx.close();
            } finally {
                byteBuf.release();
            }
        } else {
            ctx.fireChannelRead(msg);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error("服务器异常", cause);
    }
}
